

#import "texture_and_text_button_cell.h"

@interface TextureAndTextButtonCell ()
- (void)sharedInit;
- (ButtonState)currentButtonState;
- (NSImage*)imageForID:(NSInteger)imageID
           controlView:(NSView*)controlView;
@end

@implementation TextureAndTextButtonCell

// For nib instantiations
- (id)initWithCoder:(NSCoder*)decoder {
    if ((self = [super initWithCoder:decoder])) {
        [self sharedInit];
    }
    return self;
}

- (void)dealloc{
    for (int i=0; i<kButtonStateCount; ++i) {
        [imageID_[i] release];
    }
    [super dealloc];
}
- (void)sharedInit {
    [self setHighlightsBy:NSNoCellMask];
    [self setBordered:NO];
    for (int i=0; i<kButtonStateCount; ++i) {
        imageID_[i] = nil;
    }
}

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView {
    BOOL windowHasFocus = [[controlView window] isMainWindow] ||
    [[controlView window] isKeyWindow];
    CGFloat alpha = windowHasFocus ? 1.0 : 0.65;
    
    NSImage* image = imageID_[[self currentButtonState]];
    NSRect imageRect;
    imageRect.size = [image size];
    imageRect.origin = NSMakePoint(0,0);
    
    [image drawInRect:cellFrame
            fromRect:imageRect
           operation:NSCompositeSourceOver
            fraction:alpha];
    
    NSString *title = [self title];
    if (title && [title length]>0) {
        [super drawWithFrame:cellFrame inView:controlView];
    }
}

//- (void)setImageID:(NSInteger)imageID
//    forButtonState:(ButtonState)state {
//    if (imageID_[state] != imageID) {
//        imageID_[state] = imageID;
//        [[self controlView] setNeedsDisplay:YES];
//    }
//}

- (void)setImage:(NSImage *)image
    forButtonState:(int)state{
    if(imageID_[state] != image){
        imageID_[state] = image;
        [[self controlView] setNeedsDisplay:YES];        
    }
}


- (ButtonState)currentButtonState {
    if (![self isEnabled] && imageID_[kDisabledState])
        return kDisabledState;
    else if ([self isHighlighted] && imageID_[kPressedState])
        return kPressedState;
    else
        return kDefaultState;
}

//- (NSImage*)imageForID:(NSInteger)imageID
//           controlView:(NSView*)controlView {
//    if (!imageID)
//        return nil;
//
//    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
//    NSImage* image = rb.GetNativeImageNamed(imageID);
//    return image;
//}

// For programmatic instantiations
- (id)initTextCell:(NSString*)string {
    if ((self = [super initTextCell:string])) {
        [self sharedInit];
    }
    return self;
}

@end
